package org.mesh4j.sync.adapters.feed.atom;

import java.io.Writer;
import java.util.Date;

import org.kxml2.kdom.Document;
import org.kxml2.kdom.Element;
import org.mesh4j.sync.adapters.feed.ISyndicationFormat;
import org.mesh4j.sync.utils.DateHelper;

public class AtomSyndicationFormat implements ISyndicationFormat {

	private static final String ATOM_ELEMENT_FEED = "feed";
	private static final String ATOM_ELEMENT_ENTRY = "entry";
	public static final AtomSyndicationFormat INSTANCE = new AtomSyndicationFormat();

	public Element getBaseElement(Document document) {
		return document.getElement(null, ATOM_ELEMENT_FEED);
	}

	public boolean isFeedItem(Element element) {
		return ATOM_ELEMENT_ENTRY.equals(element.getName());
	}

	public Date parseDate(String dateAsString) {
		return dateAsString == null ? null : DateHelper.parseW3CDateTime(dateAsString);
	}

	public String formatDate(Date date) {
		return date == null ? "" : DateHelper.formatW3CDateTime(date);
	}

	public void writeStartDocument(Writer writer) throws Exception {
		writer.write("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
		writer.write("<feed xmlns=\"http://www.w3.org/2005/Atom\" xmlns:sx=\"http://www.microsoft.com/schemas/sse\">");
	}
	
	public void writeEndDocument(Writer writer) throws Exception {
		writer.write("</feed>");
	}

	public void writeEndItem(Writer writer) throws Exception {
		writer.write("</entry>");		
	}

	public void writeStartItem(Writer writer) throws Exception {
		writer.write("<entry>");		
	}

	public static boolean isAtom(Document document) {
		return "feed".equals(document.getRootElement().getName());
	}
	
	public String getName() {
		return "ATOM";
	}
}
